using Microsoft.EntityFrameworkCore;
using WorkFlowCore.BusinessDemo.Web.Entities;

namespace WorkFlowCore.BusinessDemo.Web.Data
{
    public class BusinessDemoDbContext : DbContext
    {
        public BusinessDemoDbContext(DbContextOptions<BusinessDemoDbContext> options)
            : base(options)
        {
        }

        public DbSet<WorkTaskStateInfo> WorkTaskStateInfos { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<Role> Roles { get; set; }
        public DbSet<UserRole> UserRoles { get; set; }
        public DbSet<Organization> Organizations { get; set; }
        public DbSet<OfficialSealApplication> OfficialSealApplications { get; set; }


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>()
                .HasIndex(u => u.EmployeeNumber)
                .IsUnique();

            // 配置UserRole复合主键
            modelBuilder.Entity<UserRole>()
                .HasKey(ur => new { ur.UserId, ur.RoleId });

            // 配置多对多关系
            modelBuilder.Entity<User>()
                .HasMany(u => u.UserRoles)
                .WithOne(ur => ur.User)
                .HasForeignKey(ur => ur.UserId);

            modelBuilder.Entity<Role>()
                .HasMany(r => r.UserRoles)
                .WithOne(ur => ur.Role)
                .HasForeignKey(ur => ur.RoleId);

            // Seed initial admin user
            modelBuilder.Entity<Role>().HasData(
                new Role
                {
                    Id = 1,
                    Code = "admin",
                    Name = "Admin"
                });

            modelBuilder.Entity<User>().HasData(
                new User
                {
                    Id = 1,
                    Name = "Admin",
                    EmployeeNumber = "admin001",
                    Phone = "13800000000",
                    Email = "admin@example.com",
                    Gender = 1,
                    Hometown = "Beijing",
                    CreateTime = new DateTime(2025, 1, 1),
                    Creator = "System",
                    UpdateTime = new DateTime(2025, 1, 1),
                    Updater = "System"
                });

            modelBuilder.Entity<UserRole>().HasData(
                new UserRole
                {
                    UserId = 1,
                    RoleId = 1
                });

            // 配置Organization的树形关系
            modelBuilder.Entity<Organization>()
                .HasOne(o => o.Parent)
                .WithMany(o => o.Children)
                .HasForeignKey(o => o.ParentId)
                .OnDelete(DeleteBehavior.Restrict);

            // 配置User-Organization关系
            modelBuilder.Entity<User>()
                .HasOne(u => u.Organization)
                .WithMany()
                .HasForeignKey(u => u.OrganizationId)
                .OnDelete(DeleteBehavior.SetNull);
        }
    }
}
